﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using Common;
using Basic.Model.Entity;
using Basic.Model.EntityManager;
using Iesi.Collections.Generic;

namespace Basic.Business
{
    public class AdminGroupAdmin
    {
        #region 添加一个AdminGroup用户组
        /// <summary>
        /// 添加一个AdminGroup用户组
        /// </summary>
        /// <param name="groupName"></param>
        /// <param name="isLocked"></param>
        public static void AddAdminGroup(string adminGroupName, string roleIds, bool isLocked)
        {
            ISession session = null;
            ITransaction trans = null;
            AdminGroup adminGroup = null;
            Role role = null;
            string[] roleIdArray = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                IList<Collision> collisions = new List<Collision>();
                roleIdArray = roleIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                
                if (String.IsNullOrEmpty(adminGroupName))
                    throw new Exception("系统用户组名称不能为空");
                if (AdminGroupManager.GetByCondition(session, -1, adminGroupName, false, false) != null)
                    throw new Exception("这个系统用户组已经存在，请换一个系统用户组名。"); 
                if (roleIdArray.Length == 0)
                    throw new Exception("你必须选择至少一个以上权限");
                adminGroup = new AdminGroup();
                adminGroup.groupName = adminGroupName;
                adminGroup.roles = new HashedSet<Role>();
                foreach (string roleId in roleIdArray)
                {
                    if (!RegularExp.IsPositiveNumber(roleId))
                        throw new Exception("所提交的权限数据中存在非法数据。");
                    
                    //进行冲突处理
                    Collision collision = new Collision();
                    collision.itemKey = "deleteRole" + roleId;
                    CollisionManager.AddItem(session, collision);
                    collisions.Add(collision);

                    role = RoleManager.Get(session, int.Parse(roleId));
                    if (role == null)
                        throw new Exception("部分权限不存在，权限ID：" + roleId);

                    adminGroup.roles.Add(role);
                }
                if (isLocked)
                    adminGroup.isLocked = 1;
                else
                    adminGroup.isLocked = 0;
                AdminGroupManager.Add(session, adminGroup);

                //删除冲突处理
                for (int i = 0; i < collisions.Count; i++)
                    CollisionManager.DeleteItem(session, collisions[i]);
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
        }
        /// <summary>
        /// 添加一个AdminGroup用户组
        /// </summary>
        /// <param name="adminGroupName"></param>
        /// <param name="roleNames"></param>
        /// <param name="isLocked"></param>
        public static void AddAdminGroup1(string adminGroupName, string roleNames, bool isLocked)
        {
            ISession session = null;
            ITransaction trans = null;
            AdminGroup adminGroup = null;
            Role role = null;
            string[] roleNameArray = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                IList<Collision> collisions = new List<Collision>();
                roleNameArray = roleNames.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                if (String.IsNullOrEmpty(adminGroupName))
                    throw new Exception("系统用户组名称不能为空");
                if (AdminGroupManager.GetByCondition(session, -1, adminGroupName, false, false) != null)
                    throw new Exception("这个系统用户组已经存在，请换一个系统用户组名。");
                if (roleNameArray.Length == 0)
                    throw new Exception("你必须选择至少一个以上权限");
                adminGroup = new AdminGroup();
                adminGroup.groupName = adminGroupName;
                adminGroup.roles = new HashedSet<Role>();
                foreach (string roleName in roleNameArray)
                {
                    role = RoleManager.GetByCondition(session, -1, roleName, false);
                    if (role == null)
                        throw new Exception("部分权限不存在，权限名为：" + roleName);
                    adminGroup.roles.Add(role);
                }
                if (isLocked)
                    adminGroup.isLocked = 1;
                else
                    adminGroup.isLocked = 0;
                AdminGroupManager.Add(session, adminGroup);

                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
        }
        #endregion

        #region 修改一个AdminGroup用户组
        /// <summary>
        /// 修改一个AdminGroup用户组
        /// </summary>
        /// <param name="adminGroupId"></param>
        /// <param name="adminGroupName"></param>
        /// <param name="roleIds"></param>
        public static void UpdateAdminGroup(int adminGroupId, string adminGroupName, string roleIds)
        {
            ISession session = null;
            ITransaction trans = null;
            AdminGroup adminGroup = null;
            AdminGroup adminGroup1 = null;
            Role role = null;
            string[] roleIdArray = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                IList<Collision> collisions = new List<Collision>();
                roleIdArray = roleIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                if (String.IsNullOrEmpty(adminGroupName))
                    throw new Exception("系统用户组名称不能为空");
                adminGroup1 = AdminGroupManager.GetByCondition(session, -1, adminGroupName, false, false);
                if (adminGroup1 != null)
                {
                    if (adminGroup1.groupId != adminGroupId)
                        throw new Exception("这个系统用户组已经存在，请换一个系统用户组名。");
                }
                if (roleIdArray.Length == 0)
                    throw new Exception("你必须选择至少一个以上权限");
                adminGroup = AdminGroupManager.GetByCondition(session, adminGroupId, null, true, true);
                adminGroup.groupName = adminGroupName;
                adminGroup.roles.Clear();
                foreach (string roleId in roleIdArray)
                {
                    if (!RegularExp.IsPositiveNumber(roleId))
                        throw new Exception("所提交的权限数据中存在非法数据。");

                    //进行冲突处理
                    Collision collision = new Collision();
                    collision.itemKey = "deleteRole" + roleId;
                    CollisionManager.AddItem(session, collision);
                    collisions.Add(collision);

                    role = RoleManager.Get(session, int.Parse(roleId));
                    if (role == null)
                        throw new Exception("部分权限不存在，权限ID：" + roleId);

                    adminGroup.roles.Add(role);
                }
                AdminGroupManager.Update(session, adminGroup);

                //删除冲突处理
                for (int i = 0; i < collisions.Count; i++)
                    CollisionManager.DeleteItem(session, collisions[i]);
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
        }
        /// <summary>
        /// 添加一个权限到系统用户组
        /// </summary>
        /// <param name="adminGroupName"></param>
        /// <param name="roleName"></param>
        public static void AddRoleToAdminGroup(string adminGroupName, string roleName)
        {
            ISession session = null;
            ITransaction trans = null;
            AdminGroup adminGroup = null;
            Role role = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                adminGroup = AdminGroupManager.GetByCondition(session, -1, adminGroupName, false, true);
                if (adminGroup == null)
                    throw new Exception("当前系统不存在这个管理员组");
                role = RoleManager.GetByCondition(session, -1, roleName, false);
                if (role == null)
                    throw new Exception("当前系统不存在这个权限定义");
                //开始冲突处理
                Collision collision = new Collision();
                collision.itemKey = "deleteAdminGroup" + adminGroup.groupId.ToString();
                CollisionManager.AddItem(session, collision);

                adminGroup.roles.Add(role);
                AdminGroupManager.Update(session, adminGroup);

                CollisionManager.DeleteItem(session, collision);
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
        }
        #endregion

        #region 删除AdminGroup对象
        /// <summary>
        /// 删除AdminGroup对象
        /// </summary>
        /// <param name="adminGroupId"></param>
        /// <returns></returns>
        public static void DeleteAdminGroup(int adminGroupId)
        {
            ISession session = null;
            ITransaction trans = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                //冲突处理
                Collision collision = new Collision();
                collision.itemKey = "deleteAdminGroup" + adminGroupId.ToString();
                CollisionManager.AddItem(session, collision);

                AdminGroup adminGroup = AdminGroupManager.GetByCondition(session, adminGroupId, null, true, true);
                if (adminGroup.admins.Count > 0)
                    throw new Exception("删除失败，该系统用户组下还有用户，请先移除用户。");
                AdminGroupManager.Delete(session, adminGroup);

                //删除冲突处理
                CollisionManager.DeleteItem(session, collision);
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
        }
        #endregion

        #region 返回查询到AdminGroup对象的result结果集
        /// <summary>
        /// 返回查询到AdminGroup对象的result结果集，主要用于填充Select下拉选择框
        /// </summary>
        /// <returns></returns>
        public static Result<Basic.VO.AdminGroup> GetAllForSelect()
        {
            Result<Basic.VO.AdminGroup> result = new Result<Basic.VO.AdminGroup>();
            IList<AdminGroup> entityData= new List<AdminGroup>();
            ISession session = null;
            ITransaction trans = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                result.total = AdminGroupManager.GetAllByConditionCount(session);
                result.data = new List<Basic.VO.AdminGroup>();
                entityData = AdminGroupManager.GetAllByCondition(session, false, false, -1, -1);
                for (int i = 0; i < entityData.Count; i++)
                {
                    Basic.VO.AdminGroup adminGroup = new Basic.VO.AdminGroup();
                    adminGroup.groupId = entityData[i].groupId;
                    adminGroup.groupName = entityData[i].groupName;
                    result.data.Add(adminGroup);
                }
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
            return result;
        }
        /// <summary>
        /// 返回查询到AdminGroup对象的result结果集，包含关联admin对象以及关联roles权限名称
        /// </summary>
        /// <param name="rowIndex"></param>
        /// <param name="rowCount"></param>
        /// <returns></returns>
        public static Result<Basic.VO.AdminGroup> GetAllAndAdminAndRole(int rowIndex, int rowCount)
        {
            Result<Basic.VO.AdminGroup> result = new Result<Basic.VO.AdminGroup>();
            IList<AdminGroup> entityData = new List<AdminGroup>();
            ISession session = null;
            ITransaction trans = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                result.total = AdminGroupManager.GetAllByConditionCount(session);
                result.data = new List<Basic.VO.AdminGroup>();
                entityData = AdminGroupManager.GetAllByCondition(session, true, true, rowIndex, rowCount);
                for (int i = 0; i < entityData.Count; i++)
                {
                    Basic.VO.AdminGroup adminGroup = new Basic.VO.AdminGroup();
                    adminGroup.groupId = entityData[i].groupId;
                    adminGroup.groupName = entityData[i].groupName;
                    adminGroup.isLocked = entityData[i].isLocked;
                    if (adminGroup.isLocked == 1)
                        adminGroup.isLockedDescription = "已锁定";
                    else
                        adminGroup.isLockedDescription = "正常";
                    if (entityData[i].admins != null)
                    {
                        adminGroup.admins = new List<Basic.VO.Admin>();
                        IEnumerator<Admin> entityAdmin = entityData[i].admins.GetEnumerator();
                        while (entityAdmin.MoveNext())
                        {
                            Basic.VO.Admin admin = new Basic.VO.Admin();
                            admin.adminId = entityAdmin.Current.adminId;
                            admin.adminName = entityAdmin.Current.adminName;
                            admin.lastLoginIp = entityAdmin.Current.lastLoginIp;
                            admin.lastLoginTime = Tools.ToDateTimeString(entityAdmin.Current.lastLoginTime);
                            admin.loginTimes = entityAdmin.Current.loginTimes;
                            adminGroup.admins.Add(admin);
                        }
                    }
                    if (entityData[i].roles != null)
                    {
                        adminGroup.roleNames = "";
                        IEnumerator<Role> entityRole = entityData[i].roles.GetEnumerator();
                        while (entityRole.MoveNext())
                        {
                            adminGroup.roleNames += entityRole.Current.roleName + ",";
                        }
                    }
                    result.data.Add(adminGroup);
                }
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
            return result;
        }
        #endregion

        #region 查询一个AdminGroup对象
        /// <summary>
        /// 查询一个AdminGroup对象
        /// </summary>
        /// <param name="adminGroupName"></param>
        /// <returns></returns>
        //public static Basic.VO.AdminGroup GetByCondition(string adminGroupName)
        //{
        //    Basic.VO.AdminGroup adminGroup = null;
        //    AdminGroup entityData = null;
        //    ISession session = null;
        //    ITransaction trans = null;
        //    try
        //    {
        //        session = NHibernateHelper.OpenSession();
        //        trans = session.BeginTransaction();
        //        entityData = AdminGroupManager.GetByCondition(session, -1, adminGroupName, false);
        //        if (entityData != null)
        //        {
        //            adminGroup = new Basic.VO.AdminGroup();
        //            adminGroup.groupId = entityData.groupId;
        //            adminGroup.groupName = entityData.groupName;
        //            adminGroup.isLocked = entityData.isLocked;
        //        }
        //        trans.Commit();
        //    }
        //    catch
        //    {
        //        if (trans != null)
        //            trans.Rollback();
        //        throw;
        //    }
        //    finally
        //    {
        //        if (session != null)
        //            session.Close();
        //    }
        //    return adminGroup;
        //}
        #endregion
    }
}
